/*
   Copyright (c) 2023 李伟国
   shiro-learner is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2. 
   You may obtain a copy of Mulan PSL v2 at:
            http://license.coscl.org.cn/MulanPSL2 
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details. 
*/

package cn.learner.service.impl;

import cn.learner.constant.enumeration.StatusConstantEnum;
import cn.learner.dto.LoginDto;
import cn.learner.entity.User;
import cn.learner.mapper.UserMapper;
import cn.learner.service.ILoginService;
import cn.learner.utils.JWTUtil;
import cn.learner.utils.RedisUtil;
import cn.learner.utils.StringUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class LoginServiceImpl implements ILoginService {
    private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);
    private static final String headerToken = "Authorization";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String login(LoginDto loginDto, HttpServletRequest request) {
        User user = userMapper.selectByUsername(loginDto.getUsername());
        if(user == null){
            throw new AuthenticationException("无此用户");
        }
        if(!user.getPassword().equals(StringUtil.getMd5(loginDto.getPassword()+user.getSalt()))){
            throw new AuthenticationException("密码错误");
        }
        long currentTimeMillis = System.currentTimeMillis();
        log.info(String.valueOf(System.currentTimeMillis()));
        String token = JWTUtil.createToken(user.getSalt(),user.getUsername(), currentTimeMillis);
        redisUtil.set(loginDto.getUsername(), currentTimeMillis, 60*30);
        return token;
    }

    @Override
    public void logout(HttpServletRequest req) {
        String accessToken = req.getHeader(headerToken);
        String username = JWTUtil.getUsername(accessToken);
        redisUtil.del(username);
        log.info("推出登录");
    }

    @Override
    public boolean register(User user) {
        // 设置盐
        user.setSalt(UUID.randomUUID().toString().substring(0,5));
        // 设置密码
        user.setPassword(StringUtil.getMd5(user.getPassword() + user.getSalt()));
        // 设置账号状态
        user.setStatus(StatusConstantEnum.ENABLE.getCode());
        int insert = userMapper.insert(user);
        return insert > 0;
    }

}
